package com.wythe.mall.activity;

import android.annotation.SuppressLint;
import android.os.Handler;
import android.os.Message;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.text.TextUtils;
import android.util.Log;
import android.view.View;
import android.widget.CheckBox;
import android.widget.ImageView;
import android.widget.TextView;
import android.widget.Toast;

import com.wythe.mall.R;
import com.wythe.mall.intf.OnRequestDataListener;
import com.wythe.mall.pay.Alipay;
import com.wythe.mall.pay.PayResult;
import com.wythe.mall.utils.ApiOkHttp;
import com.wythe.mall.utils.GotoActivity;
import com.wythe.mall.utils.ToastUtil;

import org.json.JSONException;
import org.json.JSONObject;

public class PayOrderActivity extends AppCompatActivity {
    private static final int SDK_PAY_FLAG = 1;
    private TextView mTitle, mBack;
    private ImageView mPay;
    private TextView mPrice;
    private String orderNo;
    private double payAmount;
    private CheckBox mainCheckBox;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        Bundle bundle = getIntent().getExtras();
        if (bundle != null) {
            orderNo = bundle.getString("orderNo");
            payAmount = bundle.getDouble("payAmount");
        }
        setContentView(R.layout.activity_pay_order);
        initView();
    }

    public void initView() {
        findViewById(R.id.title_left_button).setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                finish();
            }
        });

        mTitle = (TextView) findViewById(R.id.titleText);
        mPrice = (TextView) findViewById(R.id.tv_price);
        mainCheckBox = (CheckBox) findViewById(R.id.mainCheckBox);
        mainCheckBox.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                boolean isChecked = !mainCheckBox.isChecked();
                mainCheckBox.setChecked(isChecked);
            }
        });
        mPrice.setText("￥" + payAmount);
        mTitle.setText("在线支付");
        findViewById(R.id.btn_pay).setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                if (!mainCheckBox.isChecked()) {
                    ToastUtil.show(PayOrderActivity.this, "请选择支付方式");
                    return;
                } else {
                    toPay();
                }
            }
        });
    }

    private void toPay() {
        JSONObject param = new JSONObject();
        try {
            param.put("orderNo", orderNo);
            param.put("type", 1);
        } catch (JSONException e) {
            e.printStackTrace();
        }

        ApiOkHttp.choosePayMethed(this, param, new OnRequestDataListener() {
            @Override
            public void requestSuccess(int code, JSONObject data) {
                Log.e("", "requestSuccess: " + data.toString());
                try {
                    String payInfo = data.getJSONObject("data").getString("orderStr");
                    Alipay alipay = new Alipay(PayOrderActivity.this);
                    alipay.pay(payInfo);
                    alipay.setHander(mHandler);

                } catch (JSONException e) {
                    e.printStackTrace();
                }

            }

            @Override
            public void requestFailure(int code, String msg) {

            }
        });
    }

    @SuppressLint("HandlerLeak")
    private Handler mHandler = new Handler() {
        @SuppressWarnings("unused")
        public void handleMessage(Message msg) {
            switch (msg.what) {
                case SDK_PAY_FLAG: {
                    PayResult payResult = new PayResult((String) msg.obj);
                    /**
                     * 同步返回的结果必须放置到服务端进行验证（验证的规则请看https://doc.open.alipay.com/doc2/
                     * detail.htm?spm=0.0.0.0.xdvAU6&treeId=59&articleId=103665&
                     * docType=1) 建议商户依赖异步通知
                     */
                    String resultInfo = payResult.getResult();// 同步返回需要验证的信息

                    String resultStatus = payResult.getResultStatus();
                    // 判断resultStatus 为“9000”则代表支付成功，具体状态码代表含义可参考接口文档
                    if (TextUtils.equals(resultStatus, "9000")) {
                        ToastUtil.show(PayOrderActivity.this,"支付成功");
                        GotoActivity.gotoActiviy(PayOrderActivity.this,PayCompleteActivity.class);
                    } else {
                        // 判断resultStatus 为非"9000"则代表可能支付失败
                        // "8000"代表支付结果因为支付渠道原因或者系统原因还在等待支付结果确认，最终交易是否成功以服务端异步通知为准（小概率状态）
                        if (TextUtils.equals(resultStatus, "8000")) {
                            ToastUtil.show(PayOrderActivity.this,"支付结果确认中");
                        } else {
                            // 其他值就可以判断为支付失败，包括用户主动取消支付，或者系统返回的错误
                            ToastUtil.show(PayOrderActivity.this,"支付失败");
                        }
                    }
                    break;
                }
                default:
                    break;
            }
        }
    };
}
